import numpy as np
import matplotlib.pyplot as plt

# 原始数据
x = np.array([0.78, 1.56, 2.34, 3.12, 3.81])
y = np.array([2.50, 1.20, 1.12, 2.25, 4.28])

# 二次多项式拟合
coefficients = np.polyfit(x, y, 2)  # 2表示二次多项式
a, b, c = coefficients

print(f"拟合的二次多项式为: y = {a:.4f}x² + {b:.4f}x + {c:.4f}")

# 计算拟合值
y_fit = a * x**2 + b * x + c

# 计算R²值
residuals = y - y_fit
ss_res = np.sum(residuals**2)
ss_tot = np.sum((y - np.mean(y))**2)
r_squared = 1 - (ss_res / ss_tot)
print(f"R² = {r_squared:.4f}")

# 绘制结果
plt.figure(figsize=(8, 6))
plt.scatter(x, y, color='red', label='原始数据')
x_fine = np.linspace(min(x), max(x), 100)  # 精细网格用于绘制平滑曲线
plt.plot(x_fine, a*x_fine**2 + b*x_fine + c, 'b-', label='二次拟合曲线')
plt.xlabel('x')
plt.ylabel('y')
plt.title('二次多项式拟合')
plt.legend()
plt.grid(True)
plt.show()